import { createSlice, configureStore, createAsyncThunk } from '@reduxjs/toolkit'

// 新增异步需要
// 1. 引入createAsyncThunk
//2. 创建异步代码
export const asyncMsg = createAsyncThunk('yyy', () => {
  // 这里执行异步操作.一定要记得返回一个promise实例
  // return axios.get
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      //   resolve('响应回来的数据-嘿嘿嘿')
      reject()
    }, 1000)
  })
})
// 创建slice
export const countSlice = createSlice({
  name: 'xxx',
  initialState: {
    count: 10,
    msg: '嘿嘿嘿',
    loading: false,
  },
  reducers: {
    add: (state: any, action: any) => {
      // reduxjs/toolkit中允许直接修改state
      state.count = state.count + action.payload
    },
    sub: (state: any, action: any) => {
      state.count = state.count - 1
    },
  },
  // 配置处理异步的代码
  extraReducers(builder) {
    // 等待和失败的addCase一般不需要的话,可以忽略
    builder.addCase(asyncMsg.pending, (state, action) => {
      state.loading = true
    })
    builder.addCase(asyncMsg.fulfilled, (state, action) => {
      state.msg = action.payload
      state.loading = false
      console.log('异步成功')
    })
    builder.addCase(asyncMsg.rejected, (state, action) => {
      state.loading = false
      alert('异步失败')
    })
  },
})

// 创建store
const store = configureStore({
  reducer: {
    count: countSlice.reducer,
  },
})

// 3. 在创建slice中,配置extraReducer

// 监听redux中数据的变化
// store.subscribe(() => {
//   console.log(store.getState())
// })

// store.dispatch({ type: 'xxx/add', num: 3 })
// console.log(countSlice.actions.add(undefined))
// 注意: 如果使用slice中提供的actionCreator,传入参数的属性名固定就是payload
// store.dispatch(countSlice.actions.add(3))

export default store
